
import express from 'express';
import {checkLogin} from './middleWare/index.js'

import  tableModule from '../models/index.js';

const {
    usersModel,
    roleTypesModel
} = tableModule


const router = express.Router()

router.use(checkLogin)

// 查找当前用户的角色信息
router.post("/searchRoleList", async (req,res)=>{
    const {userId} = req
    let result  = await roleTypesModel.searchRoleList(userId)
    return res.json({
        code:200,
        message:"查询成功",
        data:result
    })
})


// 新增自定义角色信息  ————  每个用户独有，同时要更新用户角色
router.post("/addRoleMessage", async (req,res)=>{
    const {userId} = req
    const {roleName} = req.body
    if(userId){
        if(roleName){
            let addResRoleCode = await roleTypesModel.addRoleMessage({userId, roleName})
            if(addResRoleCode){
                // 更新用户的角色信息
                let user = await usersModel.getUserByUniqueIdentifier({userId})
                let tmpRole = typeof user.roles == 'string' ? JSON.parse(user.roles) : user.roles || []
                let updateRes = await usersModel.updateUser(userId, {currentRoleCode: addResRoleCode,roles:[...tmpRole, addResRoleCode]})

                if(updateRes){
                    return res.json({
                        code:200,
                        message:'新增成功',
                        data:true
                    })
                }else{
                    return res.status(500).json({
                        code:500,
                        message:'角色新增成功,用户信息更新失败',
                        data:null
                    })
                }
            }else{
                return res.status(500).json({
                    code:500,
                    message:'当前角色已存在，请重新添加',
                    data:null
                })
            }
        }else{
            return res.status(500).json({
                code:500,
                message:'参数缺失',
                data:null
            })
        }
    }else{
        return res.status(500).json({
            code:500,
            message:"当前用户不存在",
            data:null
        })
    }
})


export default router